import { useEffect, useState, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import IconFont from '@/components/IconFont';
import styles from './index.module.scss';

const likeComment = async () => {};

// 评论赞、踩
export default props => {
    const initState = () => ({
            count: props.count || 0,
        }),
        [state, setState] = useState(initState),
        { commentId, isLike=false, readOnly, className='' } = props,
        dispatch = useDispatch(),
        userSysCount = useSelector(store => store.main?.userSysCount || {}),
        commentIds = userSysCount[isLike ? 'commentLike' : 'commentNotLike'] || []; // 用户对评论点赞的id集合

    // 当前用户是否点赞了这个问题
    const isActive = () => commentIds.includes(parseInt(commentId));

    // 处理点击事件
    const handleClick = () => {
        let active = isActive(),
            mark = isLike ? (active ? 'CANCEL_LIKE' : 'LIKE') : (active ? 'CANCEL_DISLIKE' : 'DISLIKE');

        likeComment({commentId, mark}).then(response => {
            if(OK_CODE === response?.code) {
                let data = response?.data || {};
                // 刷新userSysCount数量，TODO
                // dispatch(updateUserCount());
                // 刷新当前问题的点赞数量
                setState(o => ({...o, count: data[isLike ? 'likeNum' : 'notLikeNum'] || 0}));
            }
        })
    };

    useEffect(() => {
        setState(o => ({...o, count: props.count}));
    }, [props.count]);

    return (
        <div
            className={`${styles['container']} ${className} ${styles['like']} ${isActive() ? styles['active'] : ''} ${readOnly ? styles['readonly'] : ''}`}
            onClick={handleClick}
        >
            <span className={styles['icon']}><IconFont name={isLike ? (isActive() ? 'icon_like_1' : 'icon_like') : (isActive() ? 'icon_cai_1' : 'icon_cai')}/></span>
            <span className={styles['label']}><i className='_meni_number'>{state.count || 0}</i></span>
        </div>
    )
}
